var app=angular.module('myApp', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
		when('/', {templateUrl: 'stbdetails.html', controller: paycont}).
		when('/cancel/', {templateUrl: 'stbdetails.html', controller: paycont}). 
		otherwise({redirectTo: '/'});
}]);

function paycont($scope, $http,$window,$location,$filter)
 {
     $scope.currentPage = 0;
    $scope.pageSize = 25;
	$scope.count = 0;    
	$scope.Math = window.Math;	
	var d = new Date();	
	$scope.typearr=[];
	$scope.stbarr=[];
	$scope.cardarr=[];
	$scope.typeidarr=[];
			
	$http.get('stb_det_tdata.php?q=2').success(function(data) {
		for(var i=0;i<data.length;i++){			
			$scope.typearr[i] = data[i].stbtype;		
			$scope.typeidarr[i] = data[i].stbid;		
		}
    });
	
	$http.get('stb_det_tdata.php?q=1').success(function(data) {
		$scope.stbdet = data;		
    });
	$http.get('stb_det_tdata.php?q=3').success(function(data) {
		for(var i=0;i<data.length;i++)
			$scope.stbarr[i] = data[i];		
    });
	$http.get('stb_det_tdata.php?q=4').success(function(data) {
		for(var i=0;i<data.length;i++)
			$scope.cardarr[i] = data[i];		
    });
	
	$scope.save= function()
	{
		if(!$scope.stbd.num || !$scope.stbd.card || !$scope.stbd.typename)
			alert("Please enter all mandatory fields marked with *");
		else{
			var valid=false;			
			var valid2=false;			
			var valid3=false;			
			for(var i =0;i<$scope.typearr.length;i++)	
				if($scope.stbd.typename == $scope.typearr[i]){											
					valid = true;	
					break;
				}
			for(var i =0;i<$scope.stbarr.length;i++)	
				if($scope.stbd.num == $scope.stbarr[i]){												
					valid2 = true;	
					break;
				}
			for(var i =0;i<$scope.cardarr.length;i++)	
				if($scope.stbd.card == $scope.cardarr[i]){												
					valid3 = true;	
					break;
				}
					
			if(!valid || !valid2 || !valid3)
			{
				var msg="";
				if(!valid)
					msg+="You entered an invalid STB type";
				if(!valid2)
					msg+="\nYou entered an unavailable STB number";
				if(!valid3)
					msg+="\nYou entered an unavailable Card number";
				alert(msg);
			}			
			else{
					var sql = 'stbdetails_cud.php?q=c&dataset='+JSON.stringify($scope.stbd);				
					$http.get(sql).success(function(data) {		
					alert("Record saved");
					//location.href=sql;
					$scope.cancel();
				});				
			} //end operation
		} //end validation			
	} //end save
	
	$scope.edit= function(id)
	{
		for(i in $scope.stbdet) {
			if($scope.stbdet[i].id == id){			       
				$scope.stbd = angular.copy($scope.stbdet[i]);
				$scope.curstb = $scope.stbd.num;
				$scope.curcard = $scope.stbd.card;				
			}
        }		
		$scope.ed = true;		
	}
	
	
	$scope.upd= function()
	{
		if(!$scope.stbd.num || !$scope.stbd.card || !$scope.stbd.typename)
			alert("Please enter all mandatory fields marked with *");
		else{
			var valid=false;			
			var valid2=false;			
			var valid3=false;	
			
			for(var i =0;i<$scope.typearr.length;i++)	
				if($scope.stbd.typename == $scope.typearr[i]){											
					valid = true;	
					break;
				}
			
			for(var i =0;i<$scope.stbarr.length;i++)				
				if($scope.stbd.num == $scope.curstb || $scope.stbd.num == $scope.stbarr[i]){					
					valid2 = true;	
					break;
				}
			for(var i =0;i<$scope.cardarr.length;i++)	
				if($scope.stbd.card == $scope.curcard || $scope.stbd.card == $scope.cardarr[i]){				
					valid3 = true;	
					break;
				}
					
			if(!valid || !valid2 || !valid3)
			{
				var msg="";
				if(!valid)
					msg+="You entered an invalid STB type";
				if(!valid2)
					msg+="\nYou entered an unavailable STB number";
				if(!valid3)
					msg+="\nYou entered an unavailable Card number";
				alert(msg);
			}			
			else{
				var sql = 'stbdetails_cud.php?q=u&dataset='+JSON.stringify($scope.stbd);			
				$http.get(sql).success(function(data) {						
				alert("Record "+$scope.stbd.id+" updated");	
				//location.href=sql;
			});	
			$scope.cancel();			
			}		
		}
	}
	
	$scope.dlt= function(id)
	{		
		var sql = 'stbdetails_cud.php?q=d&id='+id;		
		$http.get(sql).success(function(data) {				
			alert("Record "+id+" deleted");
			$scope.cancel();
		});		
	}
	
	$scope.cancel= function()
	{		 				
		$scope.activePath = null;
		$scope.activePath = $location.path('stbdetails.php');	
	};
 }
  app.filter('startingFrom', function() 
    {	
            return function(input, start) 
            {				
                start = +start; //parse to int
                return input.slice(start);
            };
    });
	
 app.directive('capitalize', function() {
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
        var capitalize = function(inputValue) {
           if(inputValue == undefined) inputValue = '';
           var capitalized = inputValue.toUpperCase();
           if(capitalized !== inputValue) {
              modelCtrl.$setViewValue(capitalized);
              modelCtrl.$render();
            }         
            return capitalized;
         }
         modelCtrl.$parsers.push(capitalize);
         capitalize(scope[attrs.ngModel]);  // capitalize initial value
     }
   };
});

 app.directive('myMaxlength', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
      var maxlength = Number(attrs.myMaxlength);
      function fromUser(text) {
          if (text.length > maxlength) {
            var transformedInput = text.substring(0, maxlength);
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
			alert(maxlength+" character limit reached...");
            return transformedInput;			
          } 
          return text;
      }
      ngModelCtrl.$parsers.push(fromUser);
    }
  }; 
});

app.directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');					  
                    }, 0);
                }
            });
    };
});
